package cn.com.assistant.controller;

import cn.com.assistant.annotation.AdminLoginToken;
import cn.com.assistant.entity.PubUserEntity;
import cn.com.assistant.entity.User;
import cn.com.assistant.mapper.PubUserMapper;
import cn.com.assistant.mapper.UserMapper;
import cn.com.assistant.model.EditPubUserModel;
import cn.com.assistant.model.PageDto;
import cn.com.assistant.model.PubUserPOJO;
import cn.com.assistant.service.PubUserService;
import cn.com.assistant.utils.RequestUtil;
import cn.com.assistant.utils.ResponseMessage;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/pubUser")
public class PubUserController {
 
    @Autowired
    PubUserService pubUserService;

    @Autowired
    PubUserMapper pubuserMapper;
 
    @GetMapping("/getAllPubUser")
    public List<PubUserEntity> queryAllPubUserList() {
        return pubUserService.queryAllPubUser();
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录(后台用户手机号验证码方式登录)", notes = "用户登录(后台用户手机号验证码方式登录)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "密码")
    })
    public ResponseMessage login(@RequestParam("username") String username,
                                 @RequestParam(name = "password") String password) {

        return pubUserService.pubUserLogin(username, password);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @ApiImplicitParam(name = "pubUserPOJO", value = "用户实体", required = true, dataType = "PubUserPOJO")
    public ResponseMessage register(@RequestBody @Valid PubUserPOJO pubUserPOJO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseMessage.validFailResponse().setMsg(bindingResult.getAllErrors());
        }
        try {
//            String targetSign = pubUserPOJO.getSign();
//            pubUserPOJO.setSign(null);
//            // 签名校验
//            String jsonString = JSON.toJSONString(pubUserPOJO);
//            String sign = MD5Util.md52(jsonString);
//            if (!targetSign.equals(sign)) {
//                return ResponseMessage.validFailResponse().setMsg("签名校验失败！");
//            }
            if(StringUtils.isEmpty(pubUserPOJO.getPassword())){
                return ResponseMessage.validFailResponse().setMsg("密码不能为空！");
            }

            if(StringUtils.isEmpty(pubUserPOJO.getConfirmPwd())){
                return ResponseMessage.validFailResponse().setMsg("确认密码不能为空！");
            }

            if(!pubUserPOJO.getPassword().equals(pubUserPOJO.getConfirmPwd())){
                return ResponseMessage.validFailResponse().setMsg("2次密码不一样，请重新输入");
            }

            //账号唯一性校验
            ResponseMessage usernameBack = pubUserService.existByUsername(pubUserPOJO.getUsername(), "-1");
            if(usernameBack.getStatus().equals(ResponseMessage.FAILED)){
                return ResponseMessage.validFailResponse().setMsg(usernameBack.getMsg());
            }

            //手机号唯一性校验
            ResponseMessage phoneBack = pubUserService.findByPhoneAndIdNot(pubUserPOJO.getPhone(), "-1");
            if(phoneBack.getStatus().equals(ResponseMessage.FAILED)){
                return ResponseMessage.validFailResponse().setMsg(phoneBack.getMsg());
            }
        } catch (Exception e) {

        }
        return pubUserService.pubUserRegister(pubUserPOJO);
    }

    public static void main(String[] args) {
        PubUserPOJO pubUserPOJO = new PubUserPOJO();
//        pubUserPOJO.setSign(null);
        pubUserPOJO.setUsername("cf");
        pubUserPOJO.setConfirmPwd("12345");
        pubUserPOJO.setPassword("12345");
        pubUserPOJO.setPhone("12345678909");
        pubUserPOJO.setUserType(0);
        String jsonString = JSON.toJSONString(pubUserPOJO);
        System.out.println(jsonString);
    }

    @ApiOperation(value = "修改密码", notes = "修改密码")
    @ApiImplicitParam(name = "editPubUserModel", value = "客户端用户密码修改模型", required = true, dataType = "EditPubUserModel")
    @PostMapping(value = "/editPwd")
    public ResponseMessage editPwd(@RequestBody @Valid EditPubUserModel editPubUserModel, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseMessage.validFailResponse().setMsg(bindingResult.getAllErrors());
        }
        ResponseMessage responseMessage = ResponseMessage.defaultResponse();
        try {
//            // 签名校验
//            String jsonString = JSONUtils.toJSONString(editPubUserModel);
//            String sign = MD5Util.md52(jsonString);
//            if (!jsonString.equals(sign)) {
//                return ResponseMessage.validFailResponse().setMsg("签名校验失败！");
//            }
            if(StringUtils.isEmpty(editPubUserModel.getPassword())){
                return ResponseMessage.validFailResponse().setMsg("密码不能为空！");
            }

            if(StringUtils.isEmpty(editPubUserModel.getConfirmPwd())){
                return ResponseMessage.validFailResponse().setMsg("确认密码不能为空！");
            }

            if(!editPubUserModel.getPassword().equals(editPubUserModel.getConfirmPwd())){
                return ResponseMessage.validFailResponse().setMsg("2次密码不一样，请重新输入");
            }
        } catch (Exception e) {
            return responseMessage.setStatus(0).setMsg("密码修改失败");
        }
        return pubUserService.updatePassword(editPubUserModel);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @ApiOperation(value = "客户端用户信息审核", notes = "客户端用户信息审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true),
            @ApiImplicitParam(name = "auditStatus", value = "审核状态", required = true),
            @ApiImplicitParam(name = "auditOpinion", value = "审核意见")
    })
    @PutMapping(value = "/audit")
    public ResponseMessage audit(@RequestParam Integer id, @RequestParam int auditStatus, @RequestParam String auditOpinion) {
        return pubUserService.examine(auditStatus, auditOpinion, id);
    }

    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @ApiOperation(value = "客户端用户信息分页列表", notes = "客户端用户信息分页列表")
    @GetMapping(value = "/page")
    public ResponseMessage findByPage(@RequestParam(value = "page", defaultValue = "0") Integer pageNum,
                                      @RequestParam(value = "size", defaultValue = "10") Integer size,
                                      HttpServletRequest request) {
        Map<String, Object> filters = RequestUtil.getParameters(request);
        IPage<User> page = new Page<>(pageNum, size);
        PageDto pageDto = new PageDto();
        pageDto.setUsername(String.valueOf(filters.get("username")));
        pageDto.setPhone(String.valueOf(filters.get("phone")));
        IPage<PubUserEntity> iPage = pubuserMapper.findByPage(page);
        return ResponseMessage.defaultResponse().setData(iPage);
    }

}